﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Threading;
using System.Text.RegularExpressions;
using System.Text;

namespace kuaishou_crawler
{
    internal class Program
    {
        public static HttpClient client = new HttpClient();
        public static string dataurl = "https://live.kuaishou.com/live_graphql";
        public static Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"accept","*/*"},
                //{"Accept-Encoding","gzip,deflate,br"},
                
                {"Connection","keep-alive"},

                { "User-Agent","PostmanRuntime/7.29.0"},

                {"Cookie","" }
            };
        public static Random rd = new Random();
        static void Main(string[] args)
        {
            var outpath = $"{Directory.GetCurrentDirectory()}/data";
            if (!Directory.Exists(outpath))
            {
                Directory.CreateDirectory(outpath);
            }
            long count = 0;
            var reqprivateFeedsQuery = getprivateFeedsQuery("userid");

            foreach (var work in reqprivateFeedsQuery.data.privateFeeds.list)
            {
                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区  
                var time = startTime.AddMilliseconds((double)work.timestamp);
                #region 获取无水印图片
                if (work.workType == "vertical" || work.workType == "multiple" || work.workType == "single" || work.workType == "ksong")
                {
                    var useroutpath = $"{outpath}/{work.user.name}/img";
                    if (!Directory.Exists(useroutpath))
                    {
                        Directory.CreateDirectory(useroutpath);
                    }

                    foreach (var imgUrl in work.imgUrls)
                    {
                        if (count > 819)
                        {
                            bool iswhile = false;
                            do
                            {
                                try
                                {
                                    var imgUrl1 = imgUrl.Replace("webp", "jpg");
                                    WebClient webClient = new WebClient();
                                    Byte[] imgData = webClient.DownloadData(imgUrl.Replace("webp", "jpg"));
                                    Stream ms = new MemoryStream(imgData);
                                    ms.Position = 0;
                                    Image img = Image.FromStream(ms);
                                    imgUrl1 = imgUrl1.Substring(imgUrl1.LastIndexOf("_"), imgUrl1.Length - imgUrl1.LastIndexOf("_"));

                                    img.Save($"{useroutpath}\\{time.ToString("yyyyMMdd")}{work.id}{count}.jpg", ImageFormat.Jpeg);
                                    webClient.Dispose();
                                    ms.Dispose();
                                    img.Dispose();
                                    Thread.Sleep(rd.Next(1000, 5000));
                                    iswhile = false;
                                }
                                catch (Exception ex)
                                {
                                    Thread.Sleep(rd.Next(1000, 5000));
                                    iswhile = true;
                                }

                            } while (iswhile);


                            Console.WriteLine(count);



                        }
                        count++;
                    }
                }
                #endregion
                ///无水印视频
                if (work.workType == "video")
                {
                    var useroutpath = $"{outpath}/{work.user.name}/video";
                    if (!Directory.Exists(useroutpath))
                    {
                        Directory.CreateDirectory(useroutpath);
                    }
                    var workurl = $"https://www.kuaishou.com/short-video/{work.id}?authorId={work.user.id}&streamSource=like&area=followxxnull";
                    var res = HttpUtils.RequestGetAsync(workurl, headers).Result;
                    //var html = res.Content.ReadAsStringAsync().Result;
                    String pattern = "\"photoUrl\":\"https(([\\s\\S])*?)\"";
                    foreach (Match item in Regex.Matches(res, pattern))
                    {
                        if (item.Value.Contains(".mp4"))
                        {
                            
                            var MP4url = item.Value.Replace("\"", "").Remove(0, 9).Replace("\\u002F", "/");
                            Uri uri = new Uri(MP4url);
                            WebClient webClient = new WebClient();
                            webClient.DownloadFile(uri, $"{useroutpath}/{time.ToString("yyyyMMdd")}{work.id}{count}.mp4");
                            webClient.Dispose();
                        }
                    }


                }
            }



            //var postdata = "{\"operationName\":\"SharePageQuery\",\"variables\":{\"photoId\":\"workid\",\"principalId\":\"userid\"},\"query\":\"query SharePageQuery($principalId: String, $photoId: String) {\\n  feedById(principalId: $principalId, photoId: $photoId) {\\n    currentWork {\\n      playUrl\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\"}";

            //var datams = HttpUtils.RequestPostAsync(dataurl, postdata, headers).Result;

           

            //ConfigurationBuilder builder = new ConfigurationBuilder();
            //builder.AddJsonStream(datams);
            //var configuration = builder.Build();
            //var collections = configuration.AsEnumerable();
            //foreach (var item in collections)
            //{
            //   var a = item.Key;
            //    var b = item.Value;
            //}
            Console.WriteLine("Hello World!");
        }
        /// <summary>
        /// 查询主页内容
        /// </summary>
        /// <param name="principalId"></param>
        /// <returns></returns>
        public static ReqprivateFeedsQuery getprivateFeedsQuery(string principalId)
        {
            var postdata = "{\"operationName\":\"privateFeedsQuery\",\"variables\":{\"principalId\":\""+principalId+"\",\"pcursor\":\"\",\"count\":999},\"query\":\"query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\\n    pcursor\\n    list {\\n      id\\n      thumbnailUrl\\n      poster\\n      workType\\n      type\\n      useVideoPlayer\\n      imgUrls\\n      imgSizes\\n      magicFace\\n      musicName\\n      caption\\n      location\\n      liked\\n      onlyFollowerCanComment\\n      relativeHeight\\n      timestamp\\n      width\\n      height\\n      counts {\\n        displayView\\n        displayLike\\n        displayComment\\n        __typename\\n      }\\n      user {\\n        id\\n        eid\\n        name\\n        avatar\\n        __typename\\n      }\\n      expTag\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\"}";
            var datams = HttpUtils.RequestPostAsync(dataurl, postdata, headers).Result;
            var privateFeedsQuery = JsonConvert.DeserializeObject<ReqprivateFeedsQuery>(datams);
            return privateFeedsQuery;

        }
    }
}
